<template>
  <d2-container class="page">
    <el-input v-model="input" placeholder="请输入内容"></el-input>
    <el-button @click="sendMessage()">发送</el-button>
    <div>
      {{ message }}
    </div>
  </d2-container>
</template>

<script>
import util from '@/libs/util'
import { socket } from "@/util/websocket.js";
export default {
  data() {
    return {
      input:'',
      loading: true,
      message:"",
      websocketCount: -1,
      //查询条件
      queryCondition: {
        type: "message",
      },
    }
  },
  created() {
    //初始化websocket对象
    //window.location.host获取ip和端口，
    //process.env.VUE_APP_WEBSOCKET_BASE_API获取请求前缀
    socket.initWebSocket(`ws:localhost:8100/websocket/` + util.cookies.get('uuid'));
    //绑定接收消息方法
    socket.websocket.onmessage = this.websocketOnMessage;
  },
  methods: {
    sendMessage(){
      let obj = {sid:util.cookies.get('uuid'),message:this.input};
      socket.sendMsg(JSON.stringify(obj));
    },
    init() {
      this.queryCondition.type = "message";
      socket.sendMsg(JSON.stringify(this.queryCondition));
    },
    websocketOnMessage(event) {
      //初始化界面时，主动向后台发送一次消息，获取数据
      this.websocketCount += 1;
      if (this.websocketCount === 0) {
        this.init();
      }
      console.log(event.data);
      let info = event.data;
      this.consumeMessage(info);
      // switch (info.type) {
      //   case "heartbeat":
      //     socket.websocketState = true;
      //     break;
      //   case "message":
      //     this.loading = true;
      //     this.$nextTick(() => {
      //       this.consumeMessage(info);
      //     })
      //     break;
      //   case "error":
      //     this.loading = false;
      //     break;
      // }
    },
    consumeMessage(info) {
      //拿到最新数据重新渲染界面
      this.message = info;
    },
  }


}
</script>

<style lang="scss" scoped>
.page {
  .logo {
    width: 120px;
  }

  .btn-group {
    color: $color-text-placehoder;
    font-size: 12px;
    line-height: 12px;
    margin-top: 0px;
    margin-bottom: 20px;

    .btn-group__btn {
      color: $color-text-sub;

      &:hover {
        color: $color-text-main;
      }

      &.btn-group__btn--link {
        color: $color-primary;
      }
    }
  }
}</style>
